<template>
  <div class="system-config">
    <el-card class="config-card" v-loading="pageLoading" element-loading-text="加载配置中...">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><Setting /></el-icon>
            <span class="header-title">系统设置</span>
          </div>
          <div class="header-right">
            <el-button type="primary" @click="saveConfig" :loading="saving">
              <IconSave />
              保存配置
            </el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTab" class="config-tabs">
        <!-- 基础设置 -->
        <el-tab-pane label="基础设置" name="basic">
          <el-form
            :model="basicForm"
            label-width="120px"
            :rules="basicRules"
            ref="basicFormRef"
          >
            <!-- 平台维护开关 -->
            <div class="section-title">
              <el-icon><Setting /></el-icon>
              <span>平台维护开关</span>
            </div>
            
            <el-form-item label="系统维护" prop="maintenance">
              <el-switch
                v-model="basicForm.maintenance"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>
            
            <el-form-item
              label="维护说明"
              v-if="basicForm.maintenance"
              prop="maintenanceMsg"
            >
              <el-input
                v-model="basicForm.maintenanceMsg"
                type="textarea"
                :rows="3"
                placeholder="请输入系统维护说明"
              />
            </el-form-item>
            
            <el-form-item label="维护计划时间" v-if="basicForm.maintenance">
              <el-date-picker
                v-model="basicForm.maintenanceTime"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
            
            <!-- 平台基本信息 -->
            <div class="section-title">
              <el-icon><InfoFilled /></el-icon>
              <span>平台基本信息</span>
            </div>
            
            <el-form-item label="平台名称" prop="platformName">
              <el-input v-model="basicForm.platformName" placeholder="请输入平台名称">
                <template #prefix>
                  <el-icon><Promotion /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input v-model="basicForm.contactPhone" placeholder="请输入联系电话">
                    <template #prefix>
                      <el-icon><Phone /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客服电话" prop="customerServicePhone">
                  <el-input v-model="basicForm.customerServicePhone" placeholder="请输入客服电话">
                    <template #prefix>
                      <el-icon><Phone /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="客服邮箱" prop="customerServiceEmail">
              <el-input v-model="basicForm.customerServiceEmail" placeholder="请输入客服邮箱">
                <template #prefix>
                  <el-icon><Message /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="客服工作时间" prop="serviceTime">
              <el-input v-model="basicForm.serviceTime" placeholder="请输入客服工作时间">
                <template #prefix>
                  <el-icon><Bell /></el-icon>
                </template>
              </el-input>
            </el-form-item>

            <el-divider content-position="center">更多设置</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="testMailConfig">
                <el-icon><Message /></el-icon>
                测试邮件配置
              </el-button>
              <el-button type="success" @click="testPhoneConfig">
                <el-icon><Phone /></el-icon>
                测试短信配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 支付设置 -->
        <el-tab-pane label="支付设置" name="payment">
          <el-form
            :model="paymentForm"
            label-width="120px"
            :rules="paymentRules"
            ref="paymentFormRef"
          >
            <!-- 微信支付配置 -->
            <div class="section-title">
              <el-icon><WalletFilled /></el-icon>
              <span>微信支付收款账号配置</span>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="AppID" prop="wxAppId">
                  <el-input
                    v-model="paymentForm.wxAppId"
                    placeholder="请输入微信AppID"
                  >
                    <template #prefix>
                      <el-icon><Key /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="商户号" prop="wxMchId">
                  <el-input
                    v-model="paymentForm.wxMchId"
                    placeholder="请输入微信商户号"
                  >
                    <template #prefix>
                      <el-icon><Shop /></el-icon>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="API密钥" prop="wxApiKey">
              <el-input
                v-model="paymentForm.wxApiKey"
                placeholder="请输入微信API密钥"
                show-password
              >
                <template #prefix>
                  <el-icon><Lock /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="API证书" prop="wxApiCert">
              <el-upload
                class="cert-upload"
                action="/api/upload/cert"
                :headers="uploadHeaders"
                :on-success="handleWxCertSuccess"
                :on-error="handleUploadError"
                :limit="1"
              >
                <el-button type="primary">上传API证书</el-button>
                <template #tip>
                  <div class="el-upload__tip">请上传微信支付API证书文件（.p12格式）</div>
                </template>
              </el-upload>
            </el-form-item>

            <!-- 支付宝配置 -->
            <div class="section-title">
              <el-icon><Money /></el-icon>
              <span>支付宝收款账号配置</span>
            </div>
            
            <el-form-item label="AppID" prop="aliAppId">
              <el-input
                v-model="paymentForm.aliAppId"
                placeholder="请输入支付宝AppID"
              >
                <template #prefix>
                  <el-icon><Key /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            
            <el-form-item label="商户私钥" prop="aliPrivateKey">
              <el-input
                v-model="paymentForm.aliPrivateKey"
                type="textarea"
                :rows="3"
                placeholder="请输入支付宝商户私钥"
                show-password
              />
            </el-form-item>
            
            <el-form-item label="支付宝公钥" prop="aliPublicKey">
              <el-input
                v-model="paymentForm.aliPublicKey"
                type="textarea"
                :rows="3"
                placeholder="请输入支付宝公钥"
              />
            </el-form-item>
            
            <!-- 银联支付配置 -->
            <div class="section-title">
              <el-icon><CreditCard /></el-icon>
              <span>银联支付收款配置</span>
            </div>
            
            <el-form-item label="商户代码" prop="unionpayMerId">
              <el-input
                v-model="paymentForm.unionpayMerId"
                placeholder="请输入银联商户代码"
              />
            </el-form-item>
            
            <el-form-item label="证书路径" prop="unionpayCertPath">
              <el-upload
                class="cert-upload"
                action="/api/upload/cert"
                :headers="uploadHeaders"
                :on-success="handleUnionpayCertSuccess"
                :on-error="handleUploadError"
                :limit="1"
              >
                <el-button type="primary">上传银联证书</el-button>
                <template #tip>
                  <div class="el-upload__tip">请上传银联支付证书文件</div>
                </template>
              </el-upload>
            </el-form-item>
            
            <!-- 平台抽成比例设置 -->
            <div class="section-title">
              <el-icon><Money /></el-icon>
              <span>平台抽成比例设置</span>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商家交易抽成" prop="merchantCommissionRate">
                  <el-input-number
                    v-model="paymentForm.merchantCommissionRate"
                    :min="0"
                    :max="20"
                    :precision="1"
                    :step="0.1"
                    style="width: 160px"
                  />
                  <span class="input-suffix">%</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="酒店预订抽成" prop="hotelCommissionRate">
                  <el-input-number
                    v-model="paymentForm.hotelCommissionRate"
                    :min="0"
                    :max="20"
                    :precision="1"
                    :step="0.1"
                    style="width: 160px"
                  />
                  <span class="input-suffix">%</span>
                </el-form-item>
              </el-col>
            </el-row>
            
            <!-- 押金设置 -->
            <div class="section-title">
              <el-icon><Money /></el-icon>
              <span>押金设置</span>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="商家保证金" prop="merchantDeposit">
                  <el-input-number
                    v-model="paymentForm.merchantDeposit"
                    :min="0"
                    :max="10000"
                    :step="100"
                    style="width: 160px"
                  />
                  <span class="input-suffix">元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="酒店保证金" prop="hotelDeposit">
                  <el-input-number
                    v-model="paymentForm.hotelDeposit"
                    :min="0"
                    :max="10000"
                    :step="100"
                    style="width: 160px"
                  />
                  <span class="input-suffix">元</span>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-divider content-position="center">支付配置测试</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="testPaymentConfig">
                <el-icon><Connection /></el-icon>
                测试支付配置
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 退款设置 -->
        <el-tab-pane label="退款设置" name="refund">
          <el-form
            :model="refundForm"
            label-width="120px"
            :rules="refundRules"
            ref="refundFormRef"
          >
            <!-- 自动退款时限 -->
            <div class="section-title">
              <el-icon><Money /></el-icon>
              <span>自动退款时限</span>
            </div>
            
            <el-form-item label="自动退款时间" prop="autoRefundTime">
              <el-input-number
                v-model="refundForm.autoRefundTime"
                :min="0"
                :max="168"
                :step="1"
                style="width: 160px"
              />
              <span class="input-suffix">小时（0表示不自动退款）</span>
            </el-form-item>
            
            <el-alert
              title="超过设定时间未发货的订单将自动退款，0表示不启用自动退款"
              type="info"
              :closable="false"
              show-icon
              style="margin-bottom: 20px;"
            />
            
            <el-divider content-position="center">退款流程规则</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="testRefundProcess">
                <el-icon><Connection /></el-icon>
                测试退款流程
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 存储设置 -->
        <el-tab-pane label="存储设置" name="storage">
          <el-form
            :model="storageForm"
            label-width="120px"
            :rules="storageRules"
            ref="storageFormRef"
          >
            <!-- 文件存储方式选择 -->
            <div class="section-title">
              <el-icon><Upload /></el-icon>
              <span>文件存储方式</span>
            </div>
            
            <el-form-item label="存储方式" prop="storageType">
              <el-radio-group v-model="storageForm.storageType">
                <el-radio-button label="local">本地存储</el-radio-button>
                <el-radio-button label="oss">阿里云OSS</el-radio-button>
                <el-radio-button label="cos">腾讯云COS</el-radio-button>
                <el-radio-button label="s3">AWS S3</el-radio-button>
              </el-radio-group>
            </el-form-item>
            
            <el-alert
              v-if="storageForm.storageType === 'local'"
              title="本地存储适用于开发环境或小型应用，生产环境推荐使用云存储服务"
              type="warning"
              :closable="false"
              show-icon
              style="margin-bottom: 20px;"
            />

            <!-- OSS/COS存储配置 -->
            <template v-if="storageForm.storageType !== 'local'">
              <div class="section-title">
                <el-icon><Key /></el-icon>
                <span>云存储配置</span>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="AccessKey" prop="storageAccessKey">
                    <el-input
                      v-model="storageForm.storageAccessKey"
                      placeholder="请输入AccessKey"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="SecretKey" prop="storageSecretKey">
                    <el-input
                      v-model="storageForm.storageSecretKey"
                      placeholder="请输入SecretKey"
                      show-password
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="Bucket名称" prop="storageBucket">
                    <el-input
                      v-model="storageForm.storageBucket"
                      placeholder="请输入Bucket名称"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="区域/终端节点" prop="storageRegion">
                    <el-input
                      v-model="storageForm.storageRegion"
                      placeholder="请输入区域或终端节点"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            
            <!-- CDN加速配置 -->
            <div class="section-title">
              <el-icon><Connection /></el-icon>
              <span>CDN加速配置</span>
            </div>
            
            <el-form-item label="启用CDN加速" prop="enableCdn">
              <el-switch v-model="storageForm.enableCdn" />
            </el-form-item>
            
            <template v-if="storageForm.enableCdn">
              <el-form-item label="CDN域名" prop="cdnDomain">
                <el-input
                  v-model="storageForm.cdnDomain"
                  placeholder="请输入CDN访问域名"
                >
                  <template #prefix>
                    <span>https://</span>
                  </template>
                </el-input>
              </el-form-item>
              
              <el-form-item label="CDN缓存刷新">
                <el-button type="warning" @click="refreshCdnCache">
                  <el-icon><Refresh /></el-icon>
                  刷新CDN缓存
                </el-button>
              </el-form-item>
            </template>
            
            <!-- 图片水印设置 -->
            <div class="section-title">
              <el-icon><Picture /></el-icon>
              <span>图片水印设置</span>
            </div>
            
            <el-form-item label="启用图片水印" prop="watermarkEnabled">
              <el-switch v-model="storageForm.watermarkEnabled" />
            </el-form-item>
            
            <template v-if="storageForm.watermarkEnabled">
              <el-form-item label="水印类型" prop="watermarkType">
                <el-radio-group v-model="storageForm.watermarkType">
                  <el-radio label="text">文字水印</el-radio>
                  <el-radio label="image">图片水印</el-radio>
                </el-radio-group>
              </el-form-item>
              
              <el-form-item label="水印文字" v-if="storageForm.watermarkType === 'text'" prop="watermarkText">
                <el-input v-model="storageForm.watermarkText" placeholder="请输入水印文字" />
              </el-form-item>
              
              <el-form-item label="水印图片" v-if="storageForm.watermarkType === 'image'" prop="watermarkImage">
                <el-upload
                  class="avatar-uploader"
                  action="/api/upload/image"
                  :headers="uploadHeaders"
                  :show-file-list="false"
                >
                  <img v-if="storageForm.watermarkImage" :src="storageForm.watermarkImage" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="水印位置" prop="watermarkPosition">
                    <el-select v-model="storageForm.watermarkPosition" placeholder="请选择水印位置">
                      <el-option label="左上角" value="topLeft" />
                      <el-option label="右上角" value="topRight" />
                      <el-option label="左下角" value="bottomLeft" />
                      <el-option label="右下角" value="bottomRight" />
                      <el-option label="中心" value="center" />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="水印透明度" prop="watermarkOpacity">
                    <el-slider
                      v-model="storageForm.watermarkOpacity"
                      :min="10"
                      :max="100"
                      :step="5"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </template>
            
            <el-divider content-position="center">存储配置测试</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="testStorageConfig">
                <el-icon><Connection /></el-icon>
                测试存储配置
              </el-button>
              <el-button type="success" @click="uploadTestFile">
                <el-icon><Upload /></el-icon>
                上传测试文件
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 敏感词管理 -->
        <el-tab-pane label="敏感词管理" name="sensitiveWords">
          <el-form
            :model="sensitiveWordsForm"
            label-width="120px"
            ref="sensitiveWordsFormRef"
            class="sensitive-words-form"
          >
            <!-- 敏感词分类和统计 -->
            <div class="section-title">
              <el-icon><Dashboard /></el-icon>
              <span>敏感词概览</span>
              <el-button type="primary" size="small" @click="openSensitiveWordTestDialog" style="margin-left: 16px;">
                <el-icon><Connection /></el-icon> 测试敏感词过滤
              </el-button>
            </div>
            
            <el-row :gutter="20" class="stats-cards-container">
              <el-col :span="8">
                <el-card shadow="hover" class="stat-overview-card">
                  <div class="stat-card-content">
                    <el-icon class="stat-icon"><DocumentChecked /></el-icon>
                    <div class="stat-info">
                      <div class="stat-label">总数量</div>
                      <div class="stat-value">{{ totalSensitiveWords }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover" class="stat-overview-card">
                  <div class="stat-card-content">
                    <el-icon class="stat-icon" style="color: #67C23A;"><Plus /></el-icon>
                    <div class="stat-info">
                      <div class="stat-label">今日新增</div>
                      <div class="stat-value">{{ todayAddedCount }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
              <el-col :span="8">
                <el-card shadow="hover" class="stat-overview-card">
                  <div class="stat-card-content">
                    <el-icon class="stat-icon" style="color: #F56C6C;"><WarningFilled /></el-icon>
                    <div class="stat-info">
                      <div class="stat-label">高风险</div>
                      <div class="stat-value">{{ highRiskCount }}</div>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 分类管理 -->
            <div class="section-title" style="margin-top: 20px;">
              <el-icon><Menu /></el-icon>
              <span>敏感词分类</span>
              <el-button type="primary" size="small" @click="openAddCategoryDialog" style="margin-left: 16px;">
                <el-icon><Plus /></el-icon> 添加分类
              </el-button>
              <el-button type="success" size="small" @click="refreshStatistics" style="margin-left: 8px;">
                <el-icon><Refresh /></el-icon> 刷新统计
              </el-button>
            </div>
            
            <div class="category-container">
              <el-empty v-if="wordCategories.length === 0" description="暂无分类数据" />
              <div v-else class="category-tags">
                <el-tag
                  v-for="item in wordCategories"
                  :key="item.id"
                  class="category-tag"
                  closable
                  :disable-transitions="false"
                  @close="handleDeleteCategory(item)"
                >
                  {{ item.name }}
                </el-tag>
              </div>
            </div>
            
            <el-divider content-position="center">敏感词管理</el-divider>
            
            <!-- 敏感词列表 -->
            <div class="section-title">
              <el-icon><Filter /></el-icon>
              <span>敏感词列表</span>
            </div>
            
            <el-form-item class="full-width-item">
              <div class="sensitive-words-header">
                <div class="search-filters">
                  <el-input
                    v-model="sensitiveWordsSearch"
                    placeholder="搜索敏感词"
                    clearable
                    @clear="loadSensitiveWords"
                    @input="debounceSearch"
                    class="search-input"
                  >
                    <template #prefix>
                      <el-icon><Search /></el-icon>
                    </template>
                    <template #append>
                      <el-button @click="searchSensitiveWords">
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                  
                  <el-select
                    v-model="selectedCategory"
                    placeholder="选择分类"
                    clearable
                    @change="filterByCategoryChange"
                    class="category-filter"
                  >
                    <el-option value="" label="全部分类" />
                    <el-option
                      v-for="item in wordCategories"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </div>
                
                <div class="action-buttons">
                  <el-button type="primary" @click="openAddWordDialog">
                    <el-icon><Plus /></el-icon>
                    添加敏感词
                  </el-button>
                  <el-button type="success" @click="importSensitiveWordsFile">
                    <el-icon><Upload /></el-icon>
                    导入敏感词
                  </el-button>
                  <el-button type="info" @click="exportSensitiveWordsFile">
                    <el-icon><Download /></el-icon>
                    导出敏感词
                  </el-button>
                </div>
              </div>
            </el-form-item>
            
            <el-form-item class="full-width-item">
              <el-table
                :data="filteredSensitiveWords"
                style="width: 100%"
                border
                v-loading="sensitiveWordsLoading"
                :header-cell-style="{background:'#f5f7fa',color:'#606266'}"
              >
                <el-table-column type="index" label="序号" width="80" align="center" />
                <el-table-column prop="word" label="敏感词" min-width="200">
                  <template #default="scope">
                    <span :class="'level-' + scope.row.level">{{ scope.row.word }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="level" label="级别" width="120" align="center">
                  <template #default="scope">
                    <el-tag :type="getTagType(scope.row.level)">
                      {{ getLevelName(scope.row.level) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="category" label="分类" width="150" align="center" />
                <el-table-column prop="createdTime" label="添加时间" width="180" />
                <el-table-column label="操作" width="180" align="center">
                  <template #default="scope">
                    <el-button
                      type="primary"
                      size="small"
                      circle
                      @click="handleEditWord(scope.row)"
                      title="编辑"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                    <el-button
                      type="danger"
                      size="small"
                      circle
                      @click="handleDeleteWord(scope.row)"
                      title="删除"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            
            <el-form-item>
              <el-pagination
                v-model:current-page="sensitiveWordsCurrentPage"
                v-model:page-size="sensitiveWordsPageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalSensitiveWords"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                background
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 内容审核 -->
        <el-tab-pane label="内容审核" name="content">
          <el-form
            :model="contentForm"
            label-width="120px"
            :rules="contentRules"
            ref="contentFormRef"
          >
            <!-- 社区内容审核规则 -->
            <div class="section-title">
              <el-icon><Connection /></el-icon>
              <span>社区内容审核规则</span>
            </div>
            
            <el-form-item label="启用内容审核" prop="contentReviewEnabled">
              <el-switch v-model="contentForm.contentReviewEnabled" />
            </el-form-item>
            
            <template v-if="contentForm.contentReviewEnabled">
              <el-form-item label="自动审核" prop="autoReviewEnabled">
                <el-switch v-model="contentForm.autoReviewEnabled" />
                <span class="description-text">启用后，系统将使用AI自动审核部分内容</span>
              </el-form-item>
              
              <el-form-item label="审核超时" prop="reviewTimeout">
                <el-input-number
                  v-model="contentForm.reviewTimeout"
                  :min="1"
                  :max="72"
                  :step="1"
                  style="width: 160px"
                />
                <span class="input-suffix">小时（超过时间未审核将自动通过）</span>
              </el-form-item>
            </template>
            
            <!-- 举报处理机制 -->
            <div class="section-title">
              <el-icon><Bell /></el-icon>
              <span>举报处理机制</span>
            </div>
            
            <el-form-item label="举报阈值" prop="reportThreshold">
              <el-input-number
                v-model="contentForm.reportThreshold"
                :min="1"
                :max="20"
                :step="1"
                style="width: 160px"
              />
              <span class="input-suffix">次（达到此数量的举报将触发处理）</span>
            </el-form-item>
            
            <el-form-item label="自动隐藏内容" prop="reportAutoHide">
              <el-switch v-model="contentForm.reportAutoHide" />
              <span class="description-text">启用后，达到举报阈值的内容将自动隐藏</span>
            </el-form-item>
            
            <el-divider content-position="center">内容审核配置测试</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="testContentFilter">
                <el-icon><Connection /></el-icon>
                测试内容审核
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 会员等级 -->
        <el-tab-pane label="会员等级" name="member">
          <el-form
            :model="memberForm"
            label-width="120px"
            :rules="memberRules"
            ref="memberFormRef"
          >
            <!-- 用户等级设置 -->
            <div class="section-title">
              <el-icon><User /></el-icon>
              <span>用户等级设置</span>
            </div>
            
            <el-form-item label="启用会员等级" prop="memberLevelEnabled">
              <el-switch v-model="memberForm.memberLevelEnabled" />
            </el-form-item>
            
            <template v-if="memberForm.memberLevelEnabled">
              <el-table :data="memberForm.levels" style="width: 100%; margin-bottom: 20px;" border>
                <el-table-column label="等级" prop="level" width="80" align="center" />
                <el-table-column label="名称" prop="name" min-width="45%">
                  <template #default="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入等级名称" />
                  </template>
                </el-table-column>
                <el-table-column label="所需积分" prop="points" min-width="45%">
                  <template #default="scope">
                    <el-input-number v-model="scope.row.points" :min="0" :step="100" />
                  </template>
                </el-table-column>
                <el-table-column label="颜色" width="100" align="center">
                  <template #default="scope">
                    <el-color-picker
                      v-model="scope.row.color"
                      size="small"
                      :predefine="predefineColors"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="scope">
                    <el-button 
                      type="danger" 
                      :icon="Delete" 
                      circle 
                      @click="handleDeleteLevel(scope.$index)"
                      :disabled="scope.row.level === 1"
                    />
                  </template>
                </el-table-column>
              </el-table>
              
              <el-form-item>
                <el-button type="primary" @click="handleAddLevel">
                  <el-icon><Plus /></el-icon>
                  添加等级
                </el-button>
              </el-form-item>
            </template>
            
            <!-- 积分规则配置 -->
            <div class="section-title">
              <el-icon><Star /></el-icon>
              <span>积分规则配置</span>
            </div>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="消费积分比" prop="pointsRules.purchase">
                  <el-input-number v-model="memberForm.pointsRules.purchase" :min="0" :max="100" :precision="1" :step="0.1" />
                  <span class="input-suffix">积分/元</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="积分抵扣比例" prop="pointsRules.redemption">
                  <el-input-number v-model="memberForm.pointsRules.redemption" :min="1" :max="1000" :step="1" />
                  <span class="input-suffix">积分 = 1元</span>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-alert
              title="消费积分比表示用户消费1元可获得的积分数量，积分抵扣比例表示多少积分可以抵扣1元"
              type="info"
              :closable="false"
              show-icon
              style="margin-bottom: 20px;"
            />
            
            <el-divider content-position="center">会员积分活动</el-divider>
            
            <el-form-item>
              <el-button type="primary" @click="configPointsActivity">
                <el-icon><Calendar /></el-icon>
                配置积分活动
              </el-button>
              <el-button type="success" @click="exportMemberData">
                <el-icon><Download /></el-icon>
                导出会员数据
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

  <!-- 敏感词管理对话框 -->
  <el-dialog
    v-model="wordDialogVisible"
    :title="wordDialogTitle"
    width="500px"
  >
    <el-form :model="currentWord" label-width="100px">
      <el-form-item label="敏感词内容" required>
        <el-input v-model="currentWord.word" placeholder="请输入敏感词内容" />
      </el-form-item>
      <el-form-item label="敏感级别" required>
        <el-radio-group v-model="currentWord.level">
          <el-radio :label="1">低</el-radio>
          <el-radio :label="2">中</el-radio>
          <el-radio :label="3">高</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="所属分类" required>
        <el-select v-model="currentWord.category" placeholder="请选择分类">
          <el-option
            v-for="item in wordCategories"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="wordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveWord">确定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 分类管理对话框 -->
  <el-dialog
    v-model="categoryDialogVisible"
    title="添加分类"
    width="400px"
  >
    <el-form :model="currentCategory" label-width="80px">
      <el-form-item label="分类名称" required>
        <el-input v-model="currentCategory.name" placeholder="请输入分类名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="categoryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveCategory">确定</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 敏感词测试对话框 -->
  <el-dialog
    v-model="sensitiveWordTestDialogVisible"
    title="敏感词测试"
    width="900px"
    destroy-on-close
    :close-on-click-modal="false"
    top="5vh"
    class="sensitive-word-test-dialog"
  >
    <div class="a-dialog-container">
      <!-- 输入区域 -->
      <div class="a-card a-input-section">
        <div class="a-card-header">
          <div class="a-card-title">
            <el-icon><Edit /></el-icon>
            <span>输入测试内容</span>
          </div>
        </div>
        <div class="a-card-body">
          <el-input
            v-model="testContent"
            type="textarea"
            :rows="5"
            placeholder="请输入需要测试的内容，检测是否包含敏感词"
            class="a-textarea"
          />
          <div class="a-action-bar">
            <el-button type="primary" @click="testSensitiveWord" :loading="testingFilter" class="a-button">
              <el-icon><Search /></el-icon>
              检测内容
            </el-button>
            <el-button @click="clearTestContent" class="a-button">
              <el-icon><Delete /></el-icon>
              清空内容
            </el-button>
          </div>
        </div>
      </div>

      <!-- 结果区域 -->
      <div v-if="testContent" class="a-card a-result-section" v-loading="testingFilter">
        <div class="a-card-header">
          <div class="a-card-title">
            <el-icon><DocumentChecked /></el-icon>
            <span>检测结果</span>
          </div>
        </div>
        <div class="a-card-body">
          <!-- 空结果提示 -->
          <el-empty 
            v-if="!testingFilter && !testResult.original" 
            description="请点击检测按钮开始分析" 
            class="a-empty-result"
          />

          <!-- 检测结果内容 -->
          <div v-if="testResult.original" class="a-result-container">
            <!-- 原始内容放在顶部 -->
            <div class="a-result-panel a-full-width">
              <div class="a-panel-header a-info">
                <el-icon><InfoFilled /></el-icon>
                <span>原始内容</span>
              </div>
              <div class="a-panel-body">
                <div class="a-content-display">{{ testResult.original }}</div>
              </div>
            </div>
            
            <!-- 三列布局的过滤结果 -->
            <div class="a-columns-container">
              <!-- 标准过滤 -->
              <div class="a-result-panel a-column" v-if="testResult.aiFiltered">
                <div class="a-panel-header a-success">
                  <el-icon><Check /></el-icon>
                  <span>标准过滤</span>
                  <div class="a-badge">基础敏感词过滤</div>
                </div>
                <div class="a-panel-body">
                  <div class="a-result-row">
                    <div class="a-result-label">过滤结果</div>
                    <div class="a-result-value">{{ testResult.aiFiltered }}</div>
                  </div>
                  
                  <div class="a-result-row" v-if="testResult.aiWords && testResult.aiWords.length > 0">
                    <div class="a-result-label">发现敏感词</div>
                    <div class="a-result-tags">
                      <el-tag
                        v-for="(word, index) in testResult.aiWords"
                        :key="'ai-'+index"
                        type="danger"
                        class="a-word-tag"
                        effect="dark"
                      >
                        {{ word }}
                      </el-tag>
                    </div>
                  </div>
                  
                  <div class="a-result-row" v-if="testResult.suggestedLevel">
                    <div class="a-result-label">推荐级别</div>
                    <el-tag class="a-level-tag" effect="light">{{ testResult.suggestedLevel }}</el-tag>
                  </div>
                </div>
              </div>
              
              <!-- 高级过滤 -->
              <div class="a-result-panel a-column" v-if="testResult.standardFiltered">
                <div class="a-panel-header a-warning">
                  <el-icon><WarningFilled /></el-icon>
                  <span>高级过滤</span>
                  <div class="a-badge">带详细敏感词信息</div>
                </div>
                <div class="a-panel-body">
                  <div class="a-result-row">
                    <div class="a-result-label">过滤结果</div>
                    <div class="a-result-value">{{ testResult.standardFiltered }}</div>
                  </div>
                  
                  <div class="a-result-row" v-if="testResult.standardWords && testResult.standardWords.length > 0">
                    <div class="a-result-label">发现敏感词</div>
                    <div class="a-result-tags">
                      <el-tag
                        v-for="(word, index) in testResult.standardWords"
                        :key="'standard-'+index"
                        type="danger"
                        class="a-word-tag"
                        effect="dark"
                      >
                        {{ word }}
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
              
              <!-- AI智能过滤 -->
              <div class="a-result-panel a-column" v-if="testResult.advancedFiltered">
                <div class="a-panel-header a-primary">
                  <el-icon><Connection /></el-icon>
                  <span>AI智能过滤</span>
                  <div class="a-badge">上下文感知敏感词检测</div>
                </div>
                <div class="a-panel-body">
                  <div class="a-result-row">
                    <div class="a-result-label">过滤结果</div>
                    <div class="a-result-value">{{ testResult.advancedFiltered }}</div>
                  </div>
                  
                  <div class="a-result-row" v-if="testResult.advancedWords && testResult.advancedWords.length > 0">
                    <div class="a-result-label">发现敏感词</div>
                    <div class="a-result-tags">
                      <el-tag
                        v-for="(word, index) in testResult.advancedWords"
                        :key="'advanced-'+index"
                        :type="getTagType(word.level)"
                        class="a-word-tag"
                        effect="dark"
                      >
                        {{ word.word }}（{{ getLevelName(word.level) }}）
                      </el-tag>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script>
// 定义组件名称以便于调试和路由缓存排除
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'SystemConfigPage',
});
</script>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, watch, computed, nextTick } from "vue";
import { useRouter, onBeforeRouteLeave } from 'vue-router';
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Setting,
  Check,
  WalletFilled,
  Key,
  Shop,
  Lock,
  Money,
  Connection,
  Upload,
  Monitor,
  CreditCard,
  Refresh,
  User,
  Promotion,
  Bell,
  Message,
  Phone,
  Picture,
  VideoPlay,
  Filter,
  InfoFilled,
  Plus,
  Download,
  Delete,
  Star,
  Present,
  Calendar,
  Edit,
  Search,
  Menu,
  Dashboard,
  DocumentChecked,
  WarningFilled,
} from "@element-plus/icons-vue";
import { IconSave } from "@arco-design/web-vue/es/icon";
import request from "@/api/axios";
import * as XLSX from 'xlsx';
import { handleApiError as globalHandleApiError } from "@/utils/errorHandler";

// 当前激活的标签页
const activeTab = ref("basic");
const saving = ref(false);
const applying = ref(false);

// 表单引用
const basicFormRef = ref(null);
const paymentFormRef = ref(null);
const refundFormRef = ref(null);
const storageFormRef = ref(null);
const contentFormRef = ref(null);
const memberFormRef = ref(null);

// 敏感词管理表单
const sensitiveWordsFormRef = ref(null);
const sensitiveWordsForm = reactive({});

// 敏感词列表状态
const sensitiveWords = ref([]);
const filteredSensitiveWords = ref([]);
const sensitiveWordsSearch = ref("");
const sensitiveWordsLoading = ref(false);
const sensitiveWordsCurrentPage = ref(1);
const sensitiveWordsPageSize = ref(10);
const totalSensitiveWords = ref(0);
const todayAddedCount = ref(0);
const highRiskCount = ref(0);
const selectedCategory = ref(""); // 添加分类筛选状态

// 敏感词分类
const wordCategories = ref([]);

// 敏感词级别映射
const levelMap = {
  1: "低",
  2: "中",
  3: "高",
};

// 对应的标签类型
const getTagType = (level) => {
  switch (level) {
    case 1: return "info";
    case 2: return "warning";
    case 3: return "danger";
    default: return "info";
  }
};

// 获取级别名称
const getLevelName = (level) => {
  return levelMap[level] || "未知";
};

// 基础设置表单
const basicForm = reactive({
  // 平台维护开关
  maintenance: false,
  maintenanceMsg: "",
  maintenanceTime: [],
  
  // 平台基本信息
  platformName: "桂林文化旅游平台",
  contactPhone: "",
  customerServicePhone: "",
  customerServiceEmail: "",
  serviceTime: "9:00-18:00",
});

// 支付设置表单
const paymentForm = reactive({
  // 微信支付收款账号配置
  wxAppId: "",
  wxMchId: "",
  wxApiKey: "",
  wxApiCert: "",
  
  // 支付宝收款账号配置
  aliAppId: "",
  aliPrivateKey: "",
  aliPublicKey: "",
  
  // 银联支付收款配置
  unionpayMerId: "",
  unionpayCertPath: "",
  
  // 平台抽成比例设置
  merchantCommissionRate: 5.0, // 商家交易抽成比例
  hotelCommissionRate: 8.0,    // 酒店预订抽成比例
  
  // 押金设置
  merchantDeposit: 2000,    // 商家保证金金额
  hotelDeposit: 5000,       // 酒店保证金金额
});

// 退款设置表单
const refundForm = reactive({
  // 自动退款时限
  autoRefundTime: 24, // 小时
});

// 存储设置表单
const storageForm = reactive({
  // 文件存储方式选择
  storageType: "oss", // local, oss, cos, s3
  
  // OSS/COS存储配置
  storageAccessKey: "",
  storageSecretKey: "",
  storageBucket: "",
  storageRegion: "",
  
  // CDN加速配置
  enableCdn: false,
  cdnDomain: "",
  
  // 图片水印设置
  watermarkEnabled: false,
  watermarkType: "text", // text, image
  watermarkText: "",
  watermarkImage: "",
  watermarkPosition: "bottomRight", // topLeft, topRight, bottomLeft, bottomRight, center
  watermarkOpacity: 30, // 百分比
});

// 内容审核表单
const contentForm = reactive({
  // 社区内容审核规则
  contentReviewEnabled: true,
  autoReviewEnabled: true,
  reviewTimeout: 24, // 小时
  
  // 举报处理机制
  reportThreshold: 3, // 举报阈值
  reportAutoHide: true, // 达到阈值自动隐藏
});

// 会员等级表单
const memberForm = reactive({
  // 用户等级设置
  memberLevelEnabled: true,
  levels: [
    { level: 1, name: "普通会员", points: 0, color: "#909399" },
    { level: 2, name: "黄金会员", points: 500, color: "#E6A23C" },
    { level: 3, name: "白金会员", points: 2000, color: "#67C23A" },
    { level: 4, name: "钻石会员", points: 5000, color: "#409EFF" }
  ],
  
  // 积分规则配置
  pointsRules: {
    purchase: 1,       // 消费1元积分
    redemption: 100    // 积分抵扣比例（多少积分可抵扣1元）
  }
});

// 预定义的颜色选择器颜色
const predefineColors = [
  '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
  '#2980b9', '#8e44ad', '#f39c12', '#27ae60', '#c0392b'
];

// 表单验证规则
const basicRules = {
  maintenanceMsg: [
    { required: true, message: "请输入维护说明", trigger: "blur" },
  ],
  contactPhone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3456789]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
  ],
  customerServicePhone: [
    { required: true, message: "请输入客服电话", trigger: "blur" },
  ],
};

const paymentRules = {
  wxAppId: [{ required: true, message: "请输入微信AppID", trigger: "blur" }],
  wxMchId: [{ required: true, message: "请输入微信商户号", trigger: "blur" }],
  wxApiKey: [{ required: true, message: "请输入微信API密钥", trigger: "blur" }],
  aliAppId: [{ required: true, message: "请输入支付宝AppID", trigger: "blur" }],
  aliPrivateKey: [
    { required: true, message: "请输入支付宝商户私钥", trigger: "blur" },
  ],
  aliPublicKey: [
    { required: true, message: "请输入支付宝公钥", trigger: "blur" },
  ],
};

const refundRules = {
  autoRefundTime: [{ required: true, message: "请设置自动退款时限", trigger: "blur" }],
};

const storageRules = {
  storageAccessKey: [{ required: true, message: "请输入AccessKey", trigger: "blur" }],
  storageSecretKey: [{ required: true, message: "请输入SecretKey", trigger: "blur" }],
  storageBucket: [{ required: true, message: "请输入Bucket名称", trigger: "blur" }],
};

const contentRules = {
  reviewTimeout: [{ required: true, message: "请设置审核超时时间", trigger: "blur" }],
};

const memberRules = {
  "levels.0.name": [{ required: true, message: "请输入等级名称", trigger: "blur" }],
};

// 上传相关
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${localStorage.getItem('token')}`
}));

// 证书上传处理函数
const handleWxCertSuccess = (response) => {
  paymentForm.wxApiCert = response.path;
  ElMessage.success("微信支付证书上传成功");
};

const handleUnionpayCertSuccess = (response) => {
  paymentForm.unionpayCertPath = response.path;
  ElMessage.success("银联支付证书上传成功");
};

const handleUploadError = () => {
  ElMessage.error("证书上传失败，请重试");
};

// 添加请求控制器管理
const abortControllers = ref(new Map());

// 添加页面加载状态
const pageLoading = ref(false);

// 全局错误处理函数
const handleApiError = (error, message = "操作失败") => {
  if (error.name === 'AbortError') {
    return; // 忽略已取消的请求
  }
  
  // 使用导入的全局错误处理函数
  return globalHandleApiError(error, message);
};

// 修改getConfigData方法
const getConfigData = async (tabName = '') => {
  pageLoading.value = true;
  try {
    // 创建新的AbortController
    const controller = new AbortController();
    if (tabName) {
      // 如果有旧的控制器，先中止
      if (abortControllers.value.has(tabName)) {
        abortControllers.value.get(tabName).abort();
      }
      abortControllers.value.set(tabName, controller);
    }
    
    // 获取基本设置
    if (!tabName || tabName === 'basic') {
      const basicRes = await request.get('/admin/settings/basic', {
        signal: controller.signal
      });
      if (basicRes && basicRes.data) {
        Object.assign(basicForm, basicRes.data);
      }
    }
    
    // 获取支付设置
    if (!tabName || tabName === 'payment') {
      const paymentRes = await request.get('/admin/settings/payment', {
        signal: controller.signal
      });
      if (paymentRes && paymentRes.data) {
        Object.assign(paymentForm, paymentRes.data);
      }
    }
    
    // 获取退款设置
    if (!tabName || tabName === 'refund') {
      const refundRes = await request.get('/admin/settings/refund', {
        signal: controller.signal
      });
      if (refundRes && refundRes.data) {
        Object.assign(refundForm, refundRes.data);
      }
    }
    
    // 获取内容审核设置
    if (!tabName || tabName === 'content') {
      const contentRes = await request.get('/admin/settings/content', {
        signal: controller.signal
      });
      if (contentRes && contentRes.data) {
        Object.assign(contentForm, contentRes.data);
      }
    }
    
    // 获取会员等级设置
    if (!tabName || tabName === 'member') {
      const memberRes = await request.get('/admin/settings/member', {
        signal: controller.signal
      });
      if (memberRes && memberRes.data) {
        Object.assign(memberForm, memberRes.data);
      }
    }
    
    if (!tabName) {
      ElMessage.success("配置数据加载成功");
    }
  } catch (error) {
    if (error.name !== 'AbortError') {
      handleApiError(error, "获取配置数据失败");
    }
  } finally {
    pageLoading.value = false;
  }
};

// 测试支付配置
const testPaymentConfig = async () => {
  try {
    await paymentFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/test/payment', paymentForm);
      ElMessage.success(res.message || "支付配置测试成功");
    } catch (error) {
      ElMessage.error(error.message || "支付配置测试失败");
    }
  } catch (error) {
    console.error("支付配置测试失败：", error);
    ElMessage.error("请先完善支付配置信息");
  }
};

// 测试退款流程
const testRefundProcess = async () => {
  try {
    await refundFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/test/refund', refundForm);
      ElMessage.success(res.message || "退款流程测试成功");
    } catch (error) {
      ElMessage.error(error.message || "退款流程测试失败");
    }
  } catch (error) {
    console.error("退款流程测试失败：", error);
    ElMessage.error("请先完善退款设置信息");
  }
};

// 测试存储配置
const testStorageConfig = async () => {
  try {
    await storageFormRef.value.validate();
    // 存储设置只在前端实现，不调用后端
    setTimeout(() => {
      ElMessage.success("存储配置测试成功");
    }, 1000);
  } catch (error) {
    console.error("存储配置测试失败：", error);
    ElMessage.error("请先完善存储配置信息");
  }
};

const uploadTestFile = () => {
  // 存储设置只在前端实现，不调用后端
  setTimeout(() => {
    ElMessage.success("测试文件上传成功");
  }, 1000);
};

// 刷新CDN缓存
const refreshCdnCache = () => {
  ElMessageBox.confirm("确定要刷新CDN缓存吗？这可能会影响用户访问速度", "刷新确认", {
    confirmButtonText: "确定刷新",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 存储设置只在前端实现，不调用后端
      setTimeout(() => {
        ElMessage.success("CDN缓存刷新请求已提交");
      }, 1000);
    })
    .catch(() => {});
};

// 测试内容审核
const testContentFilter = async () => {
  try {
    await contentFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/test/content-audit', contentForm);
      ElMessage.success(res.message || "内容审核测试成功");
    } catch (error) {
      ElMessage.error(error.message || "内容审核测试失败");
    }
  } catch (error) {
    console.error("内容审核测试失败：", error);
    ElMessage.error("请先完善内容审核设置信息");
  }
};

// 测试邮件配置
const testMailConfig = async () => {
  try {
    await basicFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/test/mail', {
        email: basicForm.customerServiceEmail
      });
      ElMessage.success(res.message || "邮件发送测试成功");
    } catch (error) {
      ElMessage.error(error.message || "邮件发送测试失败");
    }
  } catch (error) {
    console.error("邮件配置测试失败：", error);
    ElMessage.error("请先完善邮箱配置信息");
  }
};

// 测试短信配置
const testPhoneConfig = async () => {
  try {
    await basicFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/test/sms', {
        phone: basicForm.contactPhone
      });
      ElMessage.success(res.message || "短信发送测试成功");
    } catch (error) {
      ElMessage.error(error.message || "短信发送测试失败");
    }
  } catch (error) {
    console.error("短信配置测试失败：", error);
    ElMessage.error("请先完善联系电话配置信息");
  }
};

// 敏感词导入和导出函数
const importSensitiveWordsFile = async () => {
  try {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.txt,.csv,.xlsx';
    input.className = 'dynamic-upload'; // 添加标记类便于清理
    
    input.onchange = async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      
      try {
        const formData = new FormData();
        formData.append('file', file);
        
        const res = await request.post('/admin/settings/sensitive-words/import', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        ElMessage.success(res.message || "敏感词导入成功");
        // 导入成功后刷新列表
        loadSensitiveWords();
      } catch (error) {
        ElMessage.error(error.message || "敏感词导入失败");
      }
    };
    
    input.click();
  } catch (error) {
    console.error("敏感词导入失败：", error);
    ElMessage.error("敏感词导入失败，请重试");
  }
};

// 移除原有的exportSensitiveWords函数，只保留前端导出功能
const exportSensitiveWordsFile = async () => {
  try {
    sensitiveWordsLoading.value = true;
    
    // 前端直接导出，不调用后端接口
    const allWords = sensitiveWords.value.length > 0 ? 
      sensitiveWords.value.map(item => [
        item.word, 
        item.createdTime, 
        getLevelName(item.level),
        item.category
      ]) :
      [
        ["敏感词1", "2023-06-12 10:23:45", "高", "政治"],
        ["敏感词2", "2023-06-13 15:33:22", "中", "色情"],
        ["敏感词3", "2023-06-14 09:11:30", "低", "广告"]
      ];
    
    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.aoa_to_sheet([
      ['敏感词', '添加时间', '级别', '分类'],
      ...allWords
    ]);
    
    // 跟踪XLSX创建的元素以便清理
    if (!window._XLSXElements) {
      window._XLSXElements = [];
    }
    
    // 处理XLSX创建的元素
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.addedNodes.length) {
          mutation.addedNodes.forEach((node) => {
            if (node.nodeName === 'A' && node.style.display === 'none') {
              window._XLSXElements.push(node);
            }
          });
        }
      });
    });
    
    // 开始观察文档变化
    observer.observe(document.body, { childList: true });
    
    XLSX.utils.book_append_sheet(wb, ws, '敏感词库');
    XLSX.writeFile(wb, '敏感词库_' + new Date().toISOString().split('T')[0] + '.xlsx');
    
    // 停止观察
    setTimeout(() => {
      observer.disconnect();
    }, 1000);
    
    ElMessage.success("敏感词导出成功");
  } catch (error) {
    console.error("敏感词导出失败:", error);
    ElMessage.error("敏感词导出失败，请重试");
  } finally {
    sensitiveWordsLoading.value = false;
  }
};

// 会员等级相关函数
const handleDeleteLevel = (index) => {
  // 不能删除最低等级
  if (memberForm.levels[index].level === 1) {
    ElMessage.warning("不能删除最基础的会员等级");
    return;
  }
  
  // 确认删除
  ElMessageBox.confirm(`确定要删除「${memberForm.levels[index].name}」等级吗？`, "删除确认", {
    confirmButtonText: "确定删除",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    memberForm.levels.splice(index, 1);
    ElMessage.success("会员等级删除成功");
  }).catch(() => {});
};

const handleAddLevel = () => {
  // 获取最高等级
  const maxLevel = Math.max(...memberForm.levels.map(level => level.level));
  // 添加新等级
  memberForm.levels.push({
    level: maxLevel + 1,
    name: `${maxLevel + 1}级会员`,
    points: maxLevel * 1000,
    color: predefineColors[Math.floor(Math.random() * predefineColors.length)]
  });
  ElMessage.success("新等级添加成功");
};

const configPointsActivity = async () => {
  try {
    await memberFormRef.value.validate();
    try {
      const res = await request.post('/admin/settings/member/points-activity', memberForm);
      ElMessage.success(res.message || "积分活动配置成功");
    } catch (error) {
      ElMessage.error(error.message || "积分活动配置失败");
    }
  } catch (error) {
    console.error("积分活动配置失败：", error);
    ElMessage.error("请先完善会员等级信息");
  }
};

const exportMemberData = () => {
  try {
    // 生成Excel文件
    const wb = XLSX.utils.book_new();
    
    // 创建会员等级数据
    const levelSheet = XLSX.utils.aoa_to_sheet([
      ['等级', '名称', '所需积分', '等级颜色'],
      ...memberForm.levels.map(level => [
        level.level,
        level.name,
        level.points,
        level.color
      ])
    ]);
    
    // 创建积分规则数据
    const pointsSheet = XLSX.utils.aoa_to_sheet([
      ['规则名称', '设置值', '说明'],
      ['消费积分比', memberForm.pointsRules.purchase, '消费1元获得的积分数'],
      ['积分抵扣比例', memberForm.pointsRules.redemption, '多少积分可抵扣1元']
    ]);
    
    // 添加到工作簿
    XLSX.utils.book_append_sheet(wb, levelSheet, '会员等级');
    XLSX.utils.book_append_sheet(wb, pointsSheet, '积分规则');
    
    // 保存文件
    XLSX.writeFile(wb, '会员等级数据_' + new Date().toISOString().split('T')[0] + '.xlsx');
    
    ElMessage.success("会员数据导出成功");
  } catch (error) {
    console.error("会员数据导出失败：", error);
    ElMessage.error("会员数据导出失败，请重试");
  }
};

// 应用更改
const applyChanges = async () => {
  applying.value = true;
  try {
    // 验证当前表单
    const formRefs = {
      basic: basicFormRef.value,
      payment: paymentFormRef.value,
      refund: refundFormRef.value,
      storage: storageFormRef.value,
      content: contentFormRef.value,
      member: memberFormRef.value,
    };

    const currentForm = formRefs[activeTab.value];
    if (currentForm) {
      await currentForm.validate();
    }

    // 应用不同表单的设置
    try {
      let res;
      switch (activeTab.value) {
        case 'basic':
          res = await request.post('/admin/settings/basic/apply', basicForm);
          break;
        case 'payment':
          res = await request.post('/admin/settings/payment/apply', paymentForm);
          break;
        case 'refund':
          res = await request.post('/admin/settings/refund/apply', refundForm);
          break;
        case 'storage':
          // 存储设置只在前端实现
          setTimeout(() => {
            ElMessage.success("存储配置已应用到系统");
          }, 500);
          applying.value = false;
          return;
        case 'content':
          res = await request.post('/admin/settings/content/apply', contentForm);
          break;
        case 'member':
          res = await request.post('/admin/settings/member/apply', memberForm);
          break;
      }
      
      ElMessage.success(res?.message || "配置已成功应用到系统");
    } catch (error) {
      console.error("应用配置失败:", error);
      ElMessage.error(error.message || "应用配置失败，请重试");
    }
  } catch (error) {
    console.error("应用失败：", error);
    ElMessage.error("请检查配置信息是否完整");
  } finally {
    applying.value = false;
  }
};

// 保存配置
const saveConfig = async () => {
  saving.value = true;
  try {
    // 验证当前表单
    const formRefs = {
      basic: basicFormRef.value,
      payment: paymentFormRef.value,
      refund: refundFormRef.value,
      storage: storageFormRef.value,
      content: contentFormRef.value,
      member: memberFormRef.value,
    };

    const currentForm = formRefs[activeTab.value];
    if (currentForm) {
      await currentForm.validate();
    }

    // 保存不同表单的设置
    try {
      let res;
      switch (activeTab.value) {
        case 'basic':
          res = await request.post('/admin/settings/basic', basicForm);
          break;
        case 'payment':
          res = await request.post('/admin/settings/payment', paymentForm);
          break;
        case 'refund':
          res = await request.post('/admin/settings/refund', refundForm);
          break;
        case 'storage':
          // 存储设置只在前端实现
          setTimeout(() => {
            localStorage.setItem('storageSettings', JSON.stringify(storageForm));
            ElMessage.success("存储配置已保存到本地");
          }, 500);
          saving.value = false;
          return;
        case 'content':
          res = await request.post('/admin/settings/content', contentForm);
          break;
        case 'member':
          res = await request.post('/admin/settings/member', memberForm);
          break;
      }
      
      ElMessage.success(res?.message || "配置保存成功");
    } catch (error) {
      console.error("保存配置失败:", error);
      ElMessage.error(error.message || "保存配置失败，请重试");
    }
  } catch (error) {
    console.error("保存失败：", error);
    ElMessage.error("请检查配置信息是否完整");
  } finally {
    saving.value = false;
  }
};

// 加载敏感词列表
const loadSensitiveWords = async () => {
  sensitiveWordsLoading.value = true;
  try {
    // 调用API获取敏感词列表
    const res = await request.get('/admin/settings/sensitive-words', {
      params: {
        page: sensitiveWordsCurrentPage.value,
        pageSize: sensitiveWordsPageSize.value,
        keyword: sensitiveWordsSearch.value || undefined,
        category: selectedCategory.value || undefined
      }
    });
    
    if (res && res.data) {
      sensitiveWords.value = res.data.list || [];
      filteredSensitiveWords.value = sensitiveWords.value;
      totalSensitiveWords.value = res.data.total || 0;
      todayAddedCount.value = res.data.todayAdded || 0;
      highRiskCount.value = res.data.highRisk || 0;
    }
  } catch (error) {
    handleApiError(error, "获取敏感词列表失败");
    
    // 测试数据
    const testData = [
      { id: 1, word: "敏感词1", level: 3, category: "政治", createdTime: "2023-06-12 10:23:45" },
      { id: 2, word: "敏感词2", level: 2, category: "色情", createdTime: "2023-06-13 15:33:22" },
      { id: 3, word: "敏感词3", level: 1, category: "广告", createdTime: "2023-06-14 09:11:30" },
      { id: 4, word: "敏感词4", level: 3, category: "政治", createdTime: "2023-06-15 14:22:10" },
      { id: 5, word: "敏感词5", level: 1, category: "广告", createdTime: "2023-06-16 16:45:20" },
    ];
    
    sensitiveWords.value = testData;
    
    // 应用分类筛选
    if (selectedCategory.value) {
      filteredSensitiveWords.value = testData.filter(
        item => item.category === selectedCategory.value
      );
    } else {
      filteredSensitiveWords.value = testData;
    }
    
    totalSensitiveWords.value = 100;
    todayAddedCount.value = 5;
    highRiskCount.value = 25;
  } finally {
    sensitiveWordsLoading.value = false;
  }
};

// 加载敏感词分类
const loadWordCategories = async () => {
  try {
    // 调用API获取敏感词分类
    const res = await request.get('/admin/settings/sensitive-words/categories');
    
    if (res && res.data) {
      wordCategories.value = res.data || [];
    }
  } catch (error) {
    console.error("获取敏感词分类失败:", error);
    
    // 测试数据
    wordCategories.value = [
      { id: 1, name: "政治" },
      { id: 2, name: "色情" },
      { id: 3, name: "广告" },
      { id: 4, name: "暴力" },
      { id: 5, name: "其他" },
    ];
  }
};

// 刷新统计信息
const refreshStatistics = async () => {
  try {
    const res = await request.get('/admin/settings/sensitive-words/statistics');
    
    if (res && res.data) {
      totalSensitiveWords.value = res.data.total || 0;
      todayAddedCount.value = res.data.todayAdded || 0;
      highRiskCount.value = res.data.highRisk || 0;
    }
    
    ElMessage.success("统计数据刷新成功");
  } catch (error) {
    console.error("刷新统计数据失败:", error);
    ElMessage.error("刷新统计数据失败，请重试");
  }
};

// 搜索敏感词
const searchSensitiveWords = () => {
  loadSensitiveWords();
};

// 防抖处理
let timeout = null;
const debounceSearch = () => {
  if (timeout) clearTimeout(timeout);
  timeout = setTimeout(() => {
    loadSensitiveWords();
  }, 500);
};

// 分页处理
const handleSizeChange = (val) => {
  sensitiveWordsPageSize.value = val;
  loadSensitiveWords();
};

const handleCurrentChange = (val) => {
  sensitiveWordsCurrentPage.value = val;
  loadSensitiveWords();
};

// 添加敏感词对话框
const wordDialogVisible = ref(false);
const wordDialogTitle = ref("添加敏感词");
const currentWord = ref({
  id: null,
  word: "",
  level: 1,
  category: "其他",
});
const wordDialogMode = ref("add"); // add 或 edit

const openAddWordDialog = () => {
  wordDialogTitle.value = "添加敏感词";
  wordDialogMode.value = "add";
  currentWord.value = {
    id: null,
    word: "",
    level: 1,
    category: "其他",
  };
  wordDialogVisible.value = true;
};

const handleEditWord = (row) => {
  wordDialogTitle.value = "编辑敏感词";
  wordDialogMode.value = "edit";
  currentWord.value = JSON.parse(JSON.stringify(row));
  wordDialogVisible.value = true;
};

const saveWord = async () => {
  if (!currentWord.value.word) {
    ElMessage.warning("敏感词内容不能为空");
    return;
  }
  
  try {
    let res;
    
    if (wordDialogMode.value === "add") {
      res = await request.post('/admin/settings/sensitive-words', currentWord.value);
      ElMessage.success("敏感词添加成功");
    } else {
      res = await request.put(`/admin/settings/sensitive-words/${currentWord.value.id}`, currentWord.value);
      ElMessage.success("敏感词更新成功");
    }
    
    wordDialogVisible.value = false;
    loadSensitiveWords();
  } catch (error) {
    console.error("保存敏感词失败:", error);
    ElMessage.error(error.message || "操作失败，请重试");
  }
};

const handleDeleteWord = (row) => {
  ElMessageBox.confirm(`确定要删除敏感词"${row.word}"吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await request.delete(`/admin/settings/sensitive-words/${row.id}`);
        ElMessage.success("敏感词删除成功");
        loadSensitiveWords();
      } catch (error) {
        console.error("删除敏感词失败:", error);
        ElMessage.error("删除敏感词失败，请重试");
      }
    })
    .catch(() => {});
};

// 分类相关
const categoryDialogVisible = ref(false);
const currentCategory = ref({ name: "" });

const openAddCategoryDialog = () => {
  currentCategory.value = { name: "" };
  categoryDialogVisible.value = true;
};

const saveCategory = async () => {
  if (!currentCategory.value.name) {
    ElMessage.warning("分类名称不能为空");
    return;
  }
  
  try {
    await request.post('/admin/settings/sensitive-words/categories', currentCategory.value);
    ElMessage.success("分类添加成功");
    categoryDialogVisible.value = false;
    loadWordCategories();
  } catch (error) {
    console.error("保存分类失败:", error);
    ElMessage.error("操作失败，请重试");
  }
};

const handleDeleteCategory = (category) => {
  ElMessageBox.confirm(`确定要删除分类"${category.name}"吗？`, "删除确认", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await request.delete(`/admin/settings/sensitive-words/categories/${category.id}`);
        ElMessage.success("分类删除成功");
        loadWordCategories();
      } catch (error) {
        console.error("删除分类失败:", error);
        ElMessage.error("删除分类失败，请重试");
      }
    })
    .catch(() => {});
};

// 添加数据加载状态跟踪
const tabDataLoaded = reactive({
  basic: false,
  payment: false,
  refund: false,
  storage: false,
  content: false,
  member: false,
  sensitiveWords: false
});

// 按需加载当前标签页数据
const loadTabData = (tabName) => {
  if (!tabDataLoaded[tabName]) {
    switch (tabName) {
      case 'basic':
        getConfigData('basic');
        break;
      case 'payment':
        getConfigData('payment');
        break;
      case 'refund':
        getConfigData('refund');
        break;
      case 'content':
        getConfigData('content');
        break;
      case 'member':
        getConfigData('member');
        break;
      case 'sensitiveWords':
        loadSensitiveWords();
        loadWordCategories();
        break;
    }
    tabDataLoaded[tabName] = true;
  }
};

// 监听标签页变化
watch(activeTab, (newVal) => {
  loadTabData(newVal);
});

// 修改页面加载逻辑
onMounted(() => {
  // 加载当前激活标签页的数据
  loadTabData(activeTab.value);
  
  // 对于存储设置，从本地存储中读取
  if (activeTab.value === 'storage') {
    const storageSettings = localStorage.getItem('storageSettings');
    if (storageSettings) {
      try {
        const parsedSettings = JSON.parse(storageSettings);
        Object.assign(storageForm, parsedSettings);
      } catch (error) {
        console.error("解析存储设置失败:", error);
      }
    }
    tabDataLoaded.storage = true;
  }
});

// 清理所有资源的函数
const cleanupAllResources = () => {
  // 取消所有进行中的请求
  abortControllers.value.forEach(controller => {
    controller.abort();
  });
  
  // 清理定时器
  if (timeout) clearTimeout(timeout);
  
  // 清理动态创建的DOM元素
  const uploadInputs = document.querySelectorAll('input.dynamic-upload');
  uploadInputs.forEach(input => input.remove());
  
  // 清理XLSX生成的临时元素
  const hiddenElements = document.querySelectorAll('a[style*="display:none"], a[style*="display: none"]');
  hiddenElements.forEach(el => el.remove());
  
  // 重置大型数据对象
  sensitiveWords.value = [];
  filteredSensitiveWords.value = [];
  wordCategories.value = [];
  
  // 重置各种表单数据
  // (保留原有数据，避免用户信息丢失)
};

// 组件卸载前的清理
onBeforeUnmount(() => {
  cleanupAllResources();
  
  // 强制执行垃圾回收提示
  setTimeout(() => {
    window.dispatchEvent(new Event('component-destroyed'));
  }, 100);
});

// 获取路由实例
const router = useRouter();

// 在路由离开前执行清理和刷新
onBeforeRouteLeave((to, from, next) => {
  // 执行所有清理操作
  cleanupAllResources();
  
  // 让路由继续
  next();
  
  // 在下一个tick强制刷新组件
  nextTick(() => {
    // 通过URL查询参数触发刷新
    if (!to.query._refresh) {
      const query = { ...to.query, _refresh: Date.now() };
      router.replace({ path: to.path, query });
    }
  });
});

// 添加分类筛选函数
const filterByCategoryChange = () => {
  if (selectedCategory.value === "") {
    // 如果选择"全部分类"，则使用搜索框过滤
    loadSensitiveWords();
  } else {
    // 如果选择了特定分类，则进行过滤
    filteredSensitiveWords.value = sensitiveWords.value.filter(
      item => item.category === selectedCategory.value
    );
  }
};

// 敏感词测试相关状态
const sensitiveWordTestDialogVisible = ref(false);
const testContent = ref("");
const testingFilter = ref(false);
const testResult = reactive({
  original: "",
  standardFiltered: "",
  standardWords: [],
  advancedFiltered: "",
  advancedWords: [],
  aiFiltered: "",
  aiWords: [],
  suggestedLevel: ""
});

// 打开敏感词测试对话框
const openSensitiveWordTestDialog = () => {
  sensitiveWordTestDialogVisible.value = true;
  // 重置测试结果
  Object.keys(testResult).forEach(key => {
    if (Array.isArray(testResult[key])) {
      testResult[key] = [];
    } else {
      testResult[key] = "";
    }
  });
};

// 清空测试内容
const clearTestContent = () => {
  testContent.value = "";
  // 重置测试结果
  Object.keys(testResult).forEach(key => {
    if (Array.isArray(testResult[key])) {
      testResult[key] = [];
    } else {
      testResult[key] = "";
    }
  });
};

// 测试敏感词过滤
const testSensitiveWord = async () => {
  if (!testContent.value.trim()) {
    ElMessage.warning("请输入需要测试的内容");
    return;
  }
  
  testingFilter.value = true;
  try {
    // 保存原始内容
    testResult.original = testContent.value;
    
    // 同时发起三个请求
    const [standardRes, advancedRes, aiRes] = await Promise.allSettled([
      // 1. 标准敏感词过滤
      request.post('/admin/sensitive-words/filter', {
        text: testContent.value,
        level: "medium",
        replacement: "*"
      }),
      
      // 2. 高级敏感词检测
      request.post('/admin/settings/sensitive-words/check', {
        content: testContent.value,
        replace: true
      }),
      
      // 3. AI智能敏感词过滤
      request.post('/admin/system/sensitive-word-ai/smart-filter', {
        text: testContent.value
      })
    ]);
    
    // 处理标准过滤结果
    if (standardRes.status === 'fulfilled' && standardRes.value) {
      testResult.standardFiltered = standardRes.value.data || testContent.value;
      
      // 再获取发现的敏感词列表
      try {
        const wordsRes = await request.post('/admin/sensitive-words/find', {
          text: testContent.value,
          level: "medium"
        });
        testResult.standardWords = wordsRes?.data || [];
      } catch (error) {
        console.error("获取标准敏感词列表失败:", error);
        testResult.standardWords = [];
      }
    } else {
      console.error("标准敏感词过滤失败:", standardRes.reason);
      // 使用模拟数据
      testResult.standardFiltered = testContent.value.replace(/敏感|广告|色情|赌博/g, '***');
      testResult.standardWords = ['敏感', '广告', '色情', '赌博'].filter(
        word => testContent.value.includes(word)
      );
    }
    
    // 处理高级检测结果
    if (advancedRes.status === 'fulfilled' && advancedRes.value) {
      const advancedData = advancedRes.value.data || {};
      testResult.advancedFiltered = advancedData.replacedContent || testContent.value;
      testResult.advancedWords = advancedData.words || [];
    } else {
      console.error("高级敏感词检测失败:", advancedRes.reason);
      // 使用模拟数据
      testResult.advancedFiltered = testContent.value.replace(/敏感|广告|色情|赌博/g, '***');
      testResult.advancedWords = [];
      if (testContent.value.includes('敏感')) testResult.advancedWords.push({word: '敏感', level: 2, position: [0, 2]});
      if (testContent.value.includes('广告')) testResult.advancedWords.push({word: '广告', level: 1, position: [0, 2]});
      if (testContent.value.includes('色情')) testResult.advancedWords.push({word: '色情', level: 3, position: [0, 2]});
      if (testContent.value.includes('赌博')) testResult.advancedWords.push({word: '赌博', level: 2, position: [0, 2]});
    }
    
    // 处理AI智能过滤结果
    if (aiRes.status === 'fulfilled' && aiRes.value) {
      const aiData = aiRes.value;
      testResult.aiFiltered = aiData.filtered || testContent.value;
      testResult.aiWords = aiData.sensitiveWords || [];
      testResult.suggestedLevel = aiData.suggestedLevel || "medium";
    } else {
      console.error("AI智能敏感词过滤失败:", aiRes.reason);
      // 使用模拟数据 - 智能识别多种变体
      testResult.aiFiltered = testContent.value
        .replace(/敏.感/g, '***')
        .replace(/广.告/g, '***')
        .replace(/色.情/g, '***')
        .replace(/赌.博/g, '***')
        .replace(/敏感|广告|色情|赌博/g, '***');
      
      // 尝试智能匹配更多变体
      const aiDetectedWords = [];
      const patterns = [
        { regex: /敏.{0,2}感/, word: '敏感' },
        { regex: /广.{0,2}告/, word: '广告' },
        { regex: /色.{0,2}情/, word: '色情' },
        { regex: /赌.{0,2}博/, word: '赌博' }
      ];
      
      for (const pattern of patterns) {
        if (pattern.regex.test(testContent.value)) {
          aiDetectedWords.push(pattern.word);
        }
      }
      
      // 合并结果
      const standardDetected = ['敏感', '广告', '色情', '赌博'].filter(
        word => testContent.value.includes(word)
      );
      
      testResult.aiWords = [...new Set([...standardDetected, ...aiDetectedWords])];
      testResult.suggestedLevel = testResult.aiWords.includes('色情') ? "high" : "medium";
    }
    
    ElMessage.success("敏感词检测完成");
  } catch (error) {
    console.error("敏感词测试失败:", error);
    ElMessage.error("敏感词检测失败，请重试");
  } finally {
    testingFilter.value = false;
  }
};
</script>

<style scoped>
.system-config {
  padding: 20px;
}

.config-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  box-shadow: var(--el-box-shadow-light);
}

.config-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 20px;
  color: var(--el-color-primary);
}

.header-title {
  font-size: 16px;
  font-weight: 600;
}

.header-right {
  display: flex;
  gap: 12px;
}

.config-tabs {
  margin-top: 20px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 24px 0 16px;
  padding-left: 8px;
  border-left: 4px solid var(--el-color-primary);
  font-size: 15px;
  font-weight: 500;
}

.section-title:first-child {
  margin-top: 0;
}

.input-suffix {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
}

.description-text {
  margin-left: 8px;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

.cert-upload :deep(.el-upload) {
  width: 100%;
}

.cert-upload :deep(.el-upload-list) {
  margin-top: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 22px;
}

:deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 4px;
}

:deep(.el-input-number) {
  width: 180px;
}

:deep(.el-checkbox+.el-checkbox) {
  margin-left: 0;
  margin-right: 30px;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

:deep(.el-table .el-input-number) {
  width: 100px;
}

:deep(.el-tabs__item) {
  line-height: 36px;
  height: 36px;
  font-size: 14px;
}

:deep(.el-table .cell) {
  line-height: 30px;
}

/* 暗黑模式适配 */
:deep(.dark) .config-card {
  background-color: var(--el-bg-color-overlay);
}

:deep(.dark) .section-title {
  border-left-color: var(--el-color-primary-light-3);
}

:deep(.dark) .input-suffix,
:deep(.dark) .description-text {
  color: var(--el-text-color-secondary);
}

@media (max-width: 768px) {
  .config-card {
    margin: 0;
  }
  
  :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left;
    margin-bottom: 8px;
  }
  
  :deep(.el-input-number) {
    width: 100%;
  }
}

.sensitive-words-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  width: 100%;
}

.search-filters {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.search-input {
  width: 260px;
}

.category-filter {
  width: 160px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.empty-tip {
  color: #909399;
  text-align: center;
  margin: 20px 0;
}

.stat-card {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 12px;
  text-align: center;
}

.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.level-1 {
  color: #67C23A;
}

.level-2 {
  color: #E6A23C;
}

.level-3 {
  color: #F56C6C;
}

/* 暗黑模式适配 */
:deep(.dark) .stat-card {
  background-color: #304156;
}

:deep(.dark) .stat-title {
  color: #e2e2e2;
}

.stats-cards-container {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.stat-overview-card {
  flex: 1;
  padding: 16px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.stat-overview-card:hover {
  transform: translateY(-5px);
}

.stat-card-content {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.stat-icon {
  font-size: 36px;
  color: #409EFF;
  margin-right: 16px;
}

.stat-info {
  display: flex;
  flex-direction: column;
  text-align: left;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.category-container {
  margin-top: 20px;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.category-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.full-width-item {
  margin-left: 0 !important;
  margin-right: 0 !important;
  padding-left: 0 !important;
  padding-right: 0 !important;
  width: 100%;
}

.full-width-item :deep(.el-form-item__content) {
  margin-left: 0 !important;
  width: 100%;
}

.sensitive-words-form {
  width: 100%;
  padding: 0;
}

:deep(.el-tabs__content) {
  padding: 0 !important;
  overflow: visible !important;
}

:deep(.el-tab-pane) {
  padding: 0 !important;
  width: 100%;
}

:deep(.el-card__body) {
  padding: 10px !important;
}

/* 敏感词测试样式 */
.test-content {
  background-color: #f9f9f9;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.original-content {
  border-left: 4px solid #909399;
}

.filtered-content {
  border-left: 4px solid #67C23A;
}

.result-label {
  font-weight: bold;
  margin-right: 8px;
  color: #606266;
}

.sensitive-word-tag {
  margin: 4px;
}

/* 暗黑模式适配 */
:deep(.dark) .test-content {
  background-color: #304156;
  color: #e1e1e1;
}

:deep(.dark) .result-label {
  color: #a3a6ad;
}

.a-dialog-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.a-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  transition: all 0.3s ease;
}

.a-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background-color: #f9fafc;
  border-bottom: 1px solid #f2f3f5;
}

.a-card-body {
  padding: 16px;
}

.a-card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
}

.a-card-title .el-icon {
  color: #165dff;
  font-size: 18px;
}

.a-action-bar {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

.a-button {
  transition: all 0.2s;
}

.a-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.a-textarea {
  width: 100%;
  font-size: 14px;
  border-radius: 4px;
  transition: all 0.3s;
}

.a-textarea:focus {
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
}

.a-empty-result {
  text-align: center;
  color: #86909c;
  margin: 40px 0;
}

.a-result-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.a-result-panel {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s;
}

.a-result-panel:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
}

.a-panel-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  position: relative;
  overflow: hidden;
}

.a-panel-header span {
  margin-left: 8px;
  font-weight: 500;
  font-size: 15px;
}

.a-panel-header.a-info {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.a-panel-header.a-success {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.a-panel-header.a-warning {
  background-color: rgba(230, 162, 60, 0.1);
  color: #E6A23C;
}

.a-panel-header.a-primary {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

.a-panel-body {
  padding: 16px;
}

.a-badge {
  font-size: 12px;
  color: #86909c;
  background-color: rgba(229, 230, 235, 0.3);
  padding: 4px 8px;
  border-radius: 4px;
  margin-left: auto;
}

.a-result-row {
  display: flex;
  margin-bottom: 16px;
}

.a-result-row:last-child {
  margin-bottom: 0;
}

.a-result-label {
  flex: 0 0 100px;
  font-size: 14px;
  color: #4e5969;
  font-weight: 500;
}

.a-result-value {
  flex: 1;
  font-size: 14px;
  color: #1d2129;
  word-break: break-all;
}

.a-result-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.a-word-tag {
  font-size: 12px;
  padding: 4px 10px;
  border-radius: 4px;
  transition: all 0.3s;
}

.a-word-tag:hover {
  transform: scale(1.05);
}

.a-level-tag {
  font-size: 12px;
  padding: 4px 10px;
  border-radius: 4px;
}

.a-content-display {
  white-space: pre-wrap;
  word-break: break-all;
  padding: 12px;
  background-color: #f9fafc;
  border-radius: 4px;
  font-family: Consolas, Monaco, monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #4e5969;
}

/* 暗黑模式适配 */
:deep(.dark) .a-card {
  background-color: #1d2129;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2);
}

:deep(.dark) .a-card-header {
  background-color: #232324;
  border-bottom: 1px solid #333335;
}

:deep(.dark) .a-card-title {
  color: #e5e6eb;
}

:deep(.dark) .a-content-display {
  background-color: #232324;
  color: #c9cdd4;
}

:deep(.dark) .a-result-label {
  color: #a9aeb8;
}

:deep(.dark) .a-result-value {
  color: #e5e6eb;
}

:deep(.dark) .a-panel-header.a-info {
  background-color: rgba(64, 158, 255, 0.15);
}

:deep(.dark) .a-panel-header.a-success {
  background-color: rgba(103, 194, 58, 0.15);
}

:deep(.dark) .a-panel-header.a-warning {
  background-color: rgba(230, 162, 60, 0.15);
}

:deep(.dark) .a-panel-header.a-primary {
  background-color: rgba(245, 108, 108, 0.15);
}

:deep(.dark) .a-badge {
  background-color: rgba(255, 255, 255, 0.1);
  color: #a9aeb8;
}

/* 敏感词测试对话框样式覆盖 */
.sensitive-word-test-dialog :deep(.el-dialog__header) {
  background-color: #f9fafc;
  margin: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #f2f3f5;
}

.sensitive-word-test-dialog :deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 16px;
  color: #1d2129;
}

.sensitive-word-test-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.sensitive-word-test-dialog :deep(.el-dialog__headerbtn) {
  top: 16px;
}

/* 暗黑模式的对话框样式 */
:deep(.dark) .sensitive-word-test-dialog .el-dialog__header {
  background-color: #232324;
  border-bottom: 1px solid #333335;
}

:deep(.dark) .sensitive-word-test-dialog .el-dialog__title {
  color: #e5e6eb;
}

/* 添加平滑滚动 */
html {
  scroll-behavior: smooth;
}

.a-columns-container {
  display: flex;
  justify-content: space-between;
}

.a-result-panel.a-column {
  flex: 1;
  margin-right: 16px;
}

.a-result-panel.a-column:last-child {
  margin-right: 0;
}

.a-full-width {
  width: 100%;
}

.a-columns-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-top: 20px;
}

.a-result-panel.a-column {
  flex: 1;
  min-width: 250px;
  margin-right: 0;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.a-result-panel.a-full-width {
  margin-bottom: 20px;
}

.a-result-panel.a-column .a-panel-body {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.a-result-panel.a-column .a-result-row {
  display: flex;
  flex-direction: column;
  margin-bottom: 16px;
}

.a-result-panel.a-column .a-result-label {
  font-weight: 600;
  margin-bottom: 8px;
  color: #4e5969;
  font-size: 14px;
  padding-left: 4px;
  border-left: 3px solid #c9cdd4;
}

.a-result-panel.a-column .a-result-value {
  max-height: 120px;
  overflow-y: auto;
  background-color: #f9fafc;
  border-radius: 4px;
  padding: 12px;
  margin-bottom: 8px;
  word-break: break-all;
  line-height: 1.6;
  font-size: 14px;
}

.a-result-panel.a-column .a-result-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  max-height: 120px;
  overflow-y: auto;
  padding: 8px 4px;
}

.a-word-tag {
  cursor: default;
  transition: all 0.2s;
  margin: 2px;
}

.a-word-tag:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .a-columns-container {
    flex-direction: column;
  }
  
  .a-result-panel.a-column {
    width: 100%;
    margin-bottom: 20px;
  }
  
  .a-result-panel.a-column .a-result-value,
  .a-result-panel.a-column .a-result-tags {
    max-height: none;
  }
}

/* 暗黑模式适配 */
:deep(.dark) .a-result-panel.a-column .a-result-value {
  background-color: #232324;
  color: #e5e6eb;
}

:deep(.dark) .a-result-panel.a-column .a-result-label {
  color: #a9aeb8;
  border-left-color: #4e5969;
}
</style>
